package com.sinosoft.msf.base.supplier.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sinosoft.msf.base.supplier.dao.base.*;
import com.sinosoft.msf.base.supplier.expection.BizException;
import com.sinosoft.msf.base.supplier.pojo.*;
import com.sinosoft.msf.base.supplier.pojo.entity.*;
import com.sinosoft.msf.base.supplier.pojo.tyc.AutoReviewResVo;
import com.sinosoft.msf.base.supplier.props.*;
import com.sinosoft.msf.base.supplier.util.PageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class CompanyService {
    @Autowired
    CommonInterService commonInterService;
    @Autowired
    CommonBizService commonBizService;
    @Autowired
    SCompanyRequestInfoMapper requestInfoMapper;
    @Autowired
    SCompanyInfoMapper sCompanyInfoMapper;
    @Autowired
    SCompanyMarkMapper sCompanyMarkMapper;
    @Autowired
    SCompanyInfoModifyingMapper sCompanyInfoModifyingMapper;
    @Autowired
    SCompanyContractMapper sCompanyContractMapper;
    @Autowired
    SCompanyFileMapper sCompanyFileMapper;
    @Autowired
    SAuditRecordMapper sAuditRecordMapper;
    @Autowired
    SCompanyMapper sCompanyMapper;
    @Autowired
    SContractMapper sContractMapper;
    @Autowired
    CompanyFileMapper companyFileMapper;
    @Autowired
    SProjectMapper sProjectMapper;
    @Autowired
    SEvaluateRecordMapper sEvaluateRecordMapper;
    @Autowired
    SupSendService supSendService;
    @Autowired
    SCompanyScopeMapper scopeMapper;
    @Autowired
    CompanyNoticeService companyNoticeService;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Transactional
    public String saveCompany(String clientIP, CompanyInfoPojo companyInfoPojo) {

        String errorMsg = "提交成功，请等待人工审核！";
        //查询天眼查查出的企业信息
        SCompanyRequestInfo requestInfo = requestInfoMapper.selectByPrimaryKey(companyInfoPojo.getReqId());
        if (requestInfo == null) {
            throw new BizException("未查到天眼查请求信息");
        }
        EnterpriseInfoPojo enterpriseInfoPojo = JSONObject.parseObject(requestInfo.getResData(), EnterpriseInfoPojo.class);
        //查询供应商是否存在
        if ("add".equals(companyInfoPojo.getSubmitType())) {
            commonInterService.validateId(companyInfoPojo.getId());
            SCompanyInfo sCompanyInfo = new SCompanyInfo();
            sCompanyInfo.setSocialCreditCode(enterpriseInfoPojo.getSocialCreditCode());
            if (CollUtil.isNotEmpty(sCompanyInfoMapper.select(sCompanyInfo))) {
                throw new BizException("供应商已存在，如需修改信息请联系系统管理员");
            }
        } else if ("edit".equals(companyInfoPojo.getSubmitType())) {
            logger.info("修改供应商信息调用天眼查查询最新信息");
            enterpriseInfoPojo = commonInterService.queryTYCInfo(enterpriseInfoPojo.getSocialCreditCode());
        }
        //联系人手机号和邮箱格式校验
        companyInfoPojo.getContracts().forEach(concat -> {
            if (!commonInterService.isValidPhoneNumber(concat.getContactPhone())) {
                throw new BizException("联系人电话录入格式错误请核验");
            }
            if (!commonInterService.isValidEmail(concat.getContactEmail())) {
                throw new BizException("联系人邮箱录入格式错误请核验");
            }
        });
        //供应商表数据
        SCompanyInfo sCompanyInfo = new SCompanyInfo();
        BeanUtils.copyProperties(companyInfoPojo, sCompanyInfo);
        sCompanyInfo.setId(companyInfoPojo.getId());
        sCompanyInfo.setName(enterpriseInfoPojo.getName());
        sCompanyInfo.setLegalPerson(enterpriseInfoPojo.getLegalPerson());
        sCompanyInfo.setBenefiter(enterpriseInfoPojo.getBenefiter());
        sCompanyInfo.setOperateStatus(enterpriseInfoPojo.getOperateStatus());
        sCompanyInfo.setSocialCreditCode(enterpriseInfoPojo.getSocialCreditCode());
        sCompanyInfo.setBlackList(enterpriseInfoPojo.getBlackList());
        sCompanyInfo.setOperateAbnormalList(enterpriseInfoPojo.getOperateAbnormalList());
        sCompanyInfo.setAdminPunish(enterpriseInfoPojo.getAdminPunish() + "");
        sCompanyInfo.setAdminPunishDetail(enterpriseInfoPojo.getAdminPunishDetail());
        sCompanyInfo.setOwnTax(enterpriseInfoPojo.getOwnTaxCount() + "");
        sCompanyInfo.setOwnTaxDetail(enterpriseInfoPojo.getOwnTaxDetail());
        sCompanyInfo.setRegisteredAddress(enterpriseInfoPojo.getRegisteredAddress());
        sCompanyInfo.setLicenseStartDate(DateUtil.parse(enterpriseInfoPojo.getLicenseStartDate()));
        sCompanyInfo.setLicenseEndDate(DateUtil.parse(enterpriseInfoPojo.getLicenseEndDate()));
        sCompanyInfo.setAuthLetterEffectDate(companyInfoPojo.getAuthLetterEffectDate());
        sCompanyInfo.setDeleted("n");
        sCompanyInfo.setLastSearchTime(DateUtil.parse(enterpriseInfoPojo.getQueryData()));
        fetchPermitDetail(enterpriseInfoPojo, sCompanyInfo);
        sCompanyInfo.setReqId(companyInfoPojo.getReqId());
//        sCompanyInfo.setShareholderChart(enterpriseInfoPojo.getComId());
        sCompanyInfo.setTycComId(enterpriseInfoPojo.getComId());
        //处理供应商分类
        List<SCompanyScope> scopeList = new ArrayList<>();
        List<CompanyInfoPojo.ScopeItem> supplierScope = companyInfoPojo.getSupplierScope();
        for (CompanyInfoPojo.ScopeItem scopeItems : supplierScope) {
            SCompanyScope scope = new SCompanyScope();
            scope.setId(IdUtil.simpleUUID());
            scope.setBizId(sCompanyInfo.getId());
            String scopeCode = String.join(",", scopeItems.getCode());
            scope.setScopeCode(scopeCode);
            String scopeName = commonBizService.transCat(scopeCode);
            scope.setScopeName(scopeName);
            scope.setOtherName(scopeItems.getOther());
            scope.setDeleted("n");
            scope.setCreatedDate(new Date());
            scopeList.add(scope);
        }
        //自动审核判断
        OptVo optVo = new OptVo();
        AutoReviewResVo resVo = commonInterService.autoReview(enterpriseInfoPojo);
        int sta = resVo.getState();
        if (sta == 0) {
            setState(companyInfoPojo, sCompanyInfo, ComStateEnum.WAA);
            addAuditRecord(optVo, sCompanyInfo.getId(), "audit", "y", "审核通过");
        } else if (sta == 1) {
            sCompanyInfo.setState(ComStateEnum.SNO.name());
            String failMsg = String.join("；\n",resVo.getMsg());
            addAuditRecord(optVo, sCompanyInfo.getId(), "audit", "n", failMsg);
//            throw new BizException("系统校验异常、无法进行注册");
            errorMsg = "系统校验异常、无法进行注册";
        } else if (sta == 2) {
            boolean hasPass = hasAuditPass(companyInfoPojo.getId());
            setState(companyInfoPojo, sCompanyInfo, hasPass?ComStateEnum.WAA:ComStateEnum.WAL);
            String failMsg = String.join("；\n",resVo.getMsg());
            addAuditRecord(optVo, sCompanyInfo.getId(), "audit", "n", failMsg);
        }else if (sta == 3) {
            setState(companyInfoPojo, sCompanyInfo, ComStateEnum.WAA);
            String failMsg = String.join("；\n",resVo.getMsg());
            addAuditRecord(optVo, sCompanyInfo.getId(), "audit", "n", failMsg);
        }

        sCompanyInfo.setSubmitType(companyInfoPojo.getSubmitType());
        sCompanyInfo.setCreatedDate(new Date());
        sCompanyInfo.setUpdateDate(new Date());
        //联系人表数据
        List<SCompanyContract> sCompanyContractList = new ArrayList<>();
        List<Contract> contractList = companyInfoPojo.getContracts();
        contractList.forEach(contract -> {
            SCompanyContract sCompanyContract = new SCompanyContract();
            sCompanyContract.setId(IdUtil.simpleUUID());
            sCompanyContract.setCompanyId(sCompanyInfo.getId());
            sCompanyContract.setContactName(contract.getContactName());
            sCompanyContract.setContactPhone(contract.getContactPhone());
            sCompanyContract.setContactEmail(contract.getContactEmail());
            sCompanyContract.setContactPosition(contract.getContactPosition());
            sCompanyContract.setDeleted("n");
            sCompanyContract.setCreatedDate(new Date());
            sCompanyContract.setUpdateDate(new Date());
            sCompanyContractList.add(sCompanyContract);
        });
        //关联文件表
        //与我司有关交易承诺书（RTF）、无违法失信承诺书(NIF)、授权参标授权书(AGF)、其他附件（OTH）
        List<SCompanyFile> sCompanyFileList = new ArrayList<>();
        //sCompanyFileList.add(addFile(sCompanyInfo, FileTypeEnum.RTF.name(), companyInfoPojo.getRelatedTransFile()));
        //sCompanyFileList.add(addFile(sCompanyInfo, FileTypeEnum.NIF.name(), companyInfoPojo.getNoIllegalFile()));
        //sCompanyFileList.add(addFile(sCompanyInfo, FileTypeEnum.AJF.name(), companyInfoPojo.getAuthJoinFile()));
        if (CollUtil.isNotEmpty(companyInfoPojo.getRelatedTransFile())) {
            for (String filePath : companyInfoPojo.getRelatedTransFile()) {
                sCompanyFileList.add(addFile(sCompanyInfo, FileTypeEnum.RTF.name(), filePath));
            }
        }
        if (CollUtil.isNotEmpty(companyInfoPojo.getAuthJoinFile())) {
            for (String filePath : companyInfoPojo.getAuthJoinFile()) {
                sCompanyFileList.add(addFile(sCompanyInfo, FileTypeEnum.AJF.name(), filePath));
            }
        }
        if (CollUtil.isNotEmpty(companyInfoPojo.getNoIllegalFile())) {
            for (String filePath : companyInfoPojo.getNoIllegalFile()) {
                sCompanyFileList.add(addFile(sCompanyInfo, FileTypeEnum.NIF.name(), filePath));
            }
        }
        List<CompanyInfoPojo.FileVo> otherFiles = companyInfoPojo.getOtherFiles();
        if (CollUtil.isNotEmpty(otherFiles)) {
            for (CompanyInfoPojo.FileVo otherFile : otherFiles) {
                sCompanyFileList.add(addFile(sCompanyInfo, FileTypeEnum.OTH.name(), otherFile.getFilePath()));
            }
        }
        if ("add".equals(companyInfoPojo.getSubmitType())) {
            commonInterService.useId(sCompanyInfo.getId());
            //插入数据
            sCompanyInfo.setFirstSubmitTime(new Date());
            sCompanyContractMapper.insertList(sCompanyContractList);
            sCompanyFileMapper.insertList(sCompanyFileList);
            scopeMapper.insertList(scopeList);

            SCompanyInfoModifying sCompanyInfoModifying = new SCompanyInfoModifying();
            BeanUtils.copyProperties(sCompanyInfo, sCompanyInfoModifying);
            sCompanyInfoModifying.setId(IdUtil.simpleUUID());
            sCompanyInfoModifying.setBussId(companyInfoPojo.getId());
            sCompanyInfoModifyingMapper.insert(sCompanyInfoModifying);
            sCompanyInfo.setModId(sCompanyInfoModifying.getId());
            sCompanyInfoMapper.insert(sCompanyInfo);
            //联系人关联修改表的ID
            sCompanyContractList.forEach(companyContract -> {
                companyContract.setId(IdUtil.simpleUUID());
                companyContract.setCompanyId(sCompanyInfoModifying.getId());
                companyContract.setModId(sCompanyInfoModifying.getId());
            });
            sCompanyContractMapper.insertList(sCompanyContractList);
            scopeList.forEach(scope -> {
                scope.setId(IdUtil.simpleUUID());
                scope.setBizId(sCompanyInfoModifying.getId());
                scope.setModId(sCompanyInfoModifying.getId());
            });
            scopeMapper.insertList(scopeList);
            //文件关联修改表的ID
            sCompanyFileList.forEach(companyFile -> {
                companyFile.setId(IdUtil.simpleUUID());
                companyFile.setBizId(sCompanyInfoModifying.getId());
                companyFile.setModId(sCompanyInfoModifying.getId());
            });
            sCompanyFileMapper.insertList(sCompanyFileList);
            //根据审核状态发送通知
            supSendService.sendWechat(sCompanyInfo.getState(),optVo);
            //记录供应商ip地址
            companyNoticeService.saveIpAddress(clientIP, IpAddressEnum.A.name(), companyInfoPojo.getId());
        } else if ("edit".equals(companyInfoPojo.getSubmitType())) {
            SCompanyInfo orgInfo = sCompanyInfoMapper.selectByPrimaryKey(companyInfoPojo.getId());
            if (orgInfo == null) {
                throw new BizException("供应商信息不存在，请重新录入");
            }
            if (ComStateEnum.SNO.name().equalsIgnoreCase(orgInfo.getState())) {
                throw new BizException("供应商信息系统校验不通过，无法再次修改");
            }
//            if (ComStateEnum.WC.name().equals(orgInfo.getState())) {
//                //更新原供应商联系人数据为新修改数据
//                updateContract(sCompanyInfo.getId(), sCompanyContractList);
//                //更新原供应商相关文件为新修改数据
//                updateFile(sCompanyInfo.getId(), sCompanyFileList);
//                sCompanyInfoMapper.updateByPrimaryKeySelective(sCompanyInfo);
//            } else {
            //更新供应商表修改状态
            SCompanyInfoModifying sCompanyInfoModifying = new SCompanyInfoModifying();
            BeanUtils.copyProperties(sCompanyInfo, sCompanyInfoModifying);
            sCompanyInfoModifying.setId(IdUtil.simpleUUID());
            sCompanyInfoModifying.setBussId(companyInfoPojo.getId());
            sCompanyInfoModifyingMapper.insert(sCompanyInfoModifying);

            SCompanyInfo sCompanyInfoMod = new SCompanyInfo();
            sCompanyInfoMod.setId(companyInfoPojo.getId());
            sCompanyInfoMod.setModId(sCompanyInfoModifying.getId());
            sCompanyInfoMod.setModified("y");
            sCompanyInfoMod.setState(sCompanyInfo.getState());
            sCompanyInfoMod.setUpdateDate(DateUtil.date());
            sCompanyInfoMod.setSubmitType(companyInfoPojo.getSubmitType());
            sCompanyInfoMapper.updateByPrimaryKeySelective(sCompanyInfoMod);
            //联系人关联修改表的ID
            sCompanyContractList.forEach(companyContract -> {
                companyContract.setCompanyId(sCompanyInfoModifying.getId());
                companyContract.setModId(sCompanyInfoModifying.getId());
            });
            sCompanyContractMapper.insertList(sCompanyContractList);
            scopeList.forEach(scope -> {
                scope.setBizId(sCompanyInfoModifying.getId());
                scope.setModId(sCompanyInfoModifying.getId());
            });
            scopeMapper.insertList(scopeList);
            //文件关联修改表的ID
            sCompanyFileList.forEach(companyFile -> {
                companyFile.setBizId(sCompanyInfoModifying.getId());
                companyFile.setModId(sCompanyInfoModifying.getId());
            });
//            sCompanyFileMapper.insertList(sCompanyFileList);
            supSendService.sendWechat(sCompanyInfoMod.getState(),optVo);
            //记录供应商ip地址
            companyNoticeService.saveIpAddress(clientIP, IpAddressEnum.B.name(), companyInfoPojo.getId());
        }
        //相同人员信息消息生成
        companyNoticeService.sameConcatCheck(companyInfoPojo);
        return errorMsg;
    }

    private static void fetchPermitDetail(EnterpriseInfoPojo enterpriseInfoPojo, SCompanyInfo sCompanyInfo) {
        boolean permitInDate = Optional.of(enterpriseInfoPojo).map(EnterpriseInfoPojo::getPermitInDate).orElse(false);
        boolean liceIndate = Optional.of(enterpriseInfoPojo).map(EnterpriseInfoPojo::getLicenseInDate).orElse(false);
        if(liceIndate && permitInDate){
            sCompanyInfo.setPermitDetail(enterpriseInfoPojo.getPermitDetail());
            sCompanyInfo.setPermitInDate("true");
        }else{
            sCompanyInfo.setPermitInDate("false");
            String msg = enterpriseInfoPojo.getPermitDetail();
            if(!liceIndate){
                msg = "营业执照不在有效期；\n" + msg;
            }
            sCompanyInfo.setPermitDetail(msg);

        }
    }
    private static void setState(CompanyInfoPojo companyInfoPojo, SCompanyInfo sCompanyInfo, ComStateEnum waa) {
        sCompanyInfo.setState(waa.name());
    }

    private void updateContract(String orgId, List<SCompanyContract> addList) {
        SCompanyContract queryModel = new SCompanyContract();
        queryModel.setCompanyId(orgId);
        List<SCompanyContract> orgList = sCompanyContractMapper.select(queryModel);
        if (CollUtil.isNotEmpty(orgList)) {
            for (SCompanyContract contract : orgList) {
                contract.setDeleted("y");
                sCompanyContractMapper.updateByPrimaryKeySelective(contract);
            }
        }
        sCompanyContractMapper.insertList(addList);
    }

    private void updateFile(String orgId, List<SCompanyFile> addList) {
        SCompanyFile queryModel = new SCompanyFile();
        queryModel.setBizId(orgId);
        List<SCompanyFile> orgList = sCompanyFileMapper.select(queryModel);
        if (CollUtil.isNotEmpty(orgList)) {
            for (SCompanyFile contract : orgList) {
                contract.setDeleted("y");
                sCompanyFileMapper.updateByPrimaryKeySelective(contract);
            }
        }
        sCompanyFileMapper.insertList(addList);
    }

    private String toObsUrl(String obsUrl) {
        if (StrUtil.isEmpty(obsUrl)) {
            return obsUrl;
        }
        if (obsUrl.contains("?")) {
            obsUrl = obsUrl.substring(0, obsUrl.indexOf("?"));
        }
        return obsUrl;
    }
    private SCompanyFile addFile(SCompanyInfo sCompanyInfo, String fileType, String fileUrl) {
        SCompanyFile nifCompanyFile = new SCompanyFile();
        nifCompanyFile.setId(IdUtil.simpleUUID());
        nifCompanyFile.setBizType("company");
        nifCompanyFile.setBizId(sCompanyInfo.getId());
        nifCompanyFile.setFileType(fileType);
        nifCompanyFile.setFilePath(toObsUrl(fileUrl));
        nifCompanyFile.setFileName(FileUtil.getName(fileUrl));
        nifCompanyFile.setDeleted("n");
        nifCompanyFile.setCreatedDate(new Date());
        nifCompanyFile.setUpdateDate(new Date());
        return nifCompanyFile;
    }
    @Autowired
    CompanyUserRoleService userRoleService;

    public Page<CompanyInfoPojo> queryCompany(CompanyQueryReqPojo companyQueryReqPojo,OptVo optVo) {
        String userId = optVo.getUserId();
        CompanyQueryReqPojo.ParamData paramData = companyQueryReqPojo.getParamData();
        if (!"99".equals(paramData.getSupplierScopeCat())) {
            paramData.setSupplierScopeInput("");
        }
        Set<String> roles = userRoleService.queryRole(optVo);
        //查询供应商信息表
        if ("admin".equals(paramData.getAction())) {
            if (!optVo.isAdminFlag()) {
                return new Page<>(0, 0);
            }
            if ("done".equals(paramData.getActiveKey())) {
                paramData.setAdminOpt(userId);
            } else {
                paramData.setState(ComStateEnum.WAA.name());
            }
        } else if ("legal".equals(paramData.getAction())) {
            if (!optVo.isLegalFlag()) {
                return new Page<>(0, 0);
            }
            if ("done".equals(paramData.getActiveKey())) {
                paramData.setLegalOpt(userId);
            } else {
                if(roles.contains("legal2")){
                    paramData.setState(ComStateEnum.WAL2.name());
                }else if(roles.contains("legal")){
                    paramData.setState(ComStateEnum.WAL.name());
                }else{
                    paramData.setState("NN");
                }
            }
        } else if ("home".equals(paramData.getAction())) {
            if (optVo.isAdminFlag()) {
                paramData.setState(ComStateEnum.WAA.name());
            } else if (optVo.isLegalFlag()) {
                if(roles.contains("legal2")){
                    paramData.setState(ComStateEnum.WAL2.name());
                }else if(roles.contains("legal")){
                    paramData.setState(ComStateEnum.WAL.name());
                }else{
                    paramData.setState("NN");
                }
            }else{
                return new Page<>(0, 0);
            }

        }else{
            //如果不是管理员，则只能查已入库状态
            if (!optVo.isAdminFlag()){
                paramData.setState(ComStateEnum.PASS.name());
            }
        }
//        if ("done".equals(paramData.getActiveKey())) {
//            //如果查的是已审核状态
//            paramData.setOpt(userId);
//        }
        PageHelper.startPage(companyQueryReqPojo.getPageNo(), companyQueryReqPojo.getPageSize());
        Page<SCompanyInfo> sCompanyInfos = (Page<SCompanyInfo>) sCompanyMapper.selectCompanys(paramData);
        Function<SCompanyInfo, CompanyInfoPojo> transFun = sCompany -> {
            CompanyInfoPojo companyInfoPojo = new CompanyInfoPojo();
            BeanUtils.copyProperties(sCompany, companyInfoPojo);
            companyInfoPojo.setCreatedDate(DateUtil.formatDateTime(sCompany.getCreatedDate()));
            //查询联系人表
            List<Contract> contractList = commonBizService.queryContracts(sCompany.getId());
            companyInfoPojo.setContracts(contractList);
            //追加修改信息对象
            if ("y".equalsIgnoreCase(sCompany.getModified())) {
                SCompanyInfoModifying sCompanyInfoModifying = commonBizService.queryModCompany(sCompany.getModId());
                if (sCompanyInfoModifying != null) {
                    CompanyInfoPojo companyInfoMod = new CompanyInfoPojo();
                    BeanUtils.copyProperties(sCompanyInfoModifying, companyInfoMod);
                    List<Contract> contractListMod = commonBizService.queryContracts(sCompanyInfoModifying.getId());
                    companyInfoMod.setContracts(contractListMod);
                    companyInfoPojo.setCompanyInfoMod(companyInfoMod);
                }
            }
            return companyInfoPojo;
        };
        return PageUtil.transPage(sCompanyInfos, transFun);
    }

    /**
     * 查询供应商详情
     *
     * @param id
     * @return
     */
    public CompanyInfoPojo queryCompanyDetail(String id) {
        return commonBizService.queryCompanyDetail(id);
    }

    /**
     * 查询供应商详情
     *
     * @param id
     * @return
     */
    public CompanyInfoPojo queryCompanyDetail(String id, String projectId) {
        return commonBizService.queryCompanyDetail(id, projectId);
    }

    /**
     * 提交法务审核结果
     *
     * @param jsonObject
     */
    @Transactional
    public void submitLegal(JSONObject jsonObject, OptVo optVo) {
        String id = jsonObject.getString("id");
        String auditResult = jsonObject.getString("auditResult");
        String auditRemark = jsonObject.getString("auditRemark");

        SCompanyInfo sCompanyInfo = sCompanyInfoMapper.selectByPrimaryKey(id);
        if (sCompanyInfo == null) {
            throw new BizException("该供应商不存在，请核实供应商id");
        }
        String auditCat;
        String passState;
        String noState;
        if(ComStateEnum.WAL2.name().equalsIgnoreCase(sCompanyInfo.getState())){
            //法务复审
            auditCat = "legal2";
            passState = ComStateEnum.WAA.name();
            noState = ComStateEnum.LGNO2.name();
        }else if(ComStateEnum.WAL.name().equalsIgnoreCase(sCompanyInfo.getState())){
            //法务初审
            auditCat = "legal";
            passState = ComStateEnum.WAL2.name();
            noState = ComStateEnum.LGNO.name();
        }else{
            throw new BizException("该供应商已审核，请刷新页面后重试");
        }
        SAuditRecord sAuditRecord = getAuditRecord(id, auditCat, auditResult, auditRemark, optVo);
        sAuditRecordMapper.insert(sAuditRecord);
        if ("y".equalsIgnoreCase(auditResult)) {
            sCompanyInfo.setState(passState);
            supSendService.sendWechat(passState,optVo);
        } else {
            sCompanyInfo.setState(noState);
            supSendService.notifyContract(sCompanyInfo);
        }
        sCompanyInfo.setLegalAuditUser(sAuditRecord.getCreatedId());
        sCompanyInfo.setLegalAuditId(sAuditRecord.getId());
//        sCompanyInfo.setModified("n");
        sCompanyInfoMapper.updateByPrimaryKeySelective(sCompanyInfo);

    }

    /**
     * 提交管理员审核结果
     *
     * @param jsonObject
     */
    @Transactional
    public void submitAdmin(JSONObject jsonObject, OptVo optVo) {
        String id = jsonObject.getString("id");
        String auditResult = jsonObject.getString("auditResult");
        String auditRemark = jsonObject.getString("auditRemark");
        SCompanyInfo sCompanyInfo = sCompanyInfoMapper.selectByPrimaryKey(id);
        if (sCompanyInfo == null) {
            throw new BizException("该供应商不存在，请核实供应商id");
        }
        if (ComStateEnum.PASS.name().equals(sCompanyInfo.getState())) {
            throw new BizException("该供应商已审核通过，不可以重复审核");
        }
        SAuditRecord sAuditRecord = getAuditRecord(id, "admin", auditResult, auditRemark, optVo);
        sAuditRecordMapper.insert(sAuditRecord);
        //人工审核后修改供应商表状态（最新修改的记录表状态改为审核通过或不通过）

        SCompanyInfoModifying sCompanyInfoModifying = null;
        if ("y".equalsIgnoreCase(sCompanyInfo.getModified())) {
            sCompanyInfoModifying = commonBizService.queryModCompany(sCompanyInfo.getModId());
        }
        if ("y".equalsIgnoreCase(auditResult)) {
            if (sCompanyInfoModifying != null) {
                //更新原供应商联系人数据为新修改数据
                //todo 此处改为更新原供应商联系人数据为新修改数据
                sContractMapper.updateDeletedState(id);
                //sContractMapper.updateCompanyId(sCompanyInfoModifying.getId(), id);
                SCompanyContract contractQuery = new SCompanyContract();
                contractQuery.setCompanyId(sCompanyInfoModifying.getId());
                List<SCompanyContract> contractlist = sCompanyContractMapper.select(contractQuery);
                contractlist.forEach(contract ->   {
                    contract.setId(IdUtil.simpleUUID());
                    contract.setCompanyId(id);
                    contract.setModId(id);
                });
                sCompanyContractMapper.insertList(contractlist);
                //更新供应商经营范围
                sContractMapper.updateCompanyScopeState(id);
                //sContractMapper.updateCompanyScopeId(sCompanyInfoModifying.getId(), id);
                SCompanyScope scopeQuery = new SCompanyScope();
                scopeQuery.setBizId(sCompanyInfoModifying.getId());
                List<SCompanyScope> scopeList = scopeMapper.select(scopeQuery);
                scopeList.forEach(scope -> {
                    scope.setId(IdUtil.simpleUUID());
                    scope.setBizId(id);
                    scope.setModId(id);
                });
                scopeMapper.insertList(scopeList);
                //更新原供应商相关文件为新修改数据
                companyFileMapper.updateDeletedState(id);
                //companyFileMapper.updateBizId(sCompanyInfoModifying.getId(), id);
                SCompanyFile fileQuery = new SCompanyFile();
                fileQuery.setBizId(sCompanyInfoModifying.getId());
                List<SCompanyFile> fileList = sCompanyFileMapper.select(fileQuery);
                fileList.forEach(file -> {
                    file.setId(IdUtil.simpleUUID());
                    file.setBizId(id);
                    file.setModId(id);
                });
                sCompanyFileMapper.insertList(fileList);
                // 解决供应商修改后营业执照止期为空不更新问题
                if (sCompanyInfoModifying.getLicenseEndDate() == null && sCompanyInfo.getLicenseEndDate() != null) {
                    sCompanyMapper.updateLicenseEndDate(sCompanyInfo.getId());
                    logger.info("更新营业执照结束日期为空成功");
                }
                //更新原供应商信息为修改后的数据
                BeanUtils.copyProperties(sCompanyInfoModifying, sCompanyInfo);
                sCompanyInfo.setId(id);
            }
            sCompanyInfo.setModified("n");
            //sCompanyInfo.setModId("n");
            sCompanyInfo.setState(ComStateEnum.PASS.name());
        } else {
            sCompanyInfo.setState(ComStateEnum.ADNO.name());
            supSendService.notifyContract(sCompanyInfo);
        }
        sCompanyInfo.setAdminAuditUser(sAuditRecord.getCreatedId());
        sCompanyInfo.setAdminAuditId(sAuditRecord.getId());
        sCompanyInfoMapper.updateByPrimaryKeySelective(sCompanyInfo);

    }

    private static SAuditRecord getAuditRecord(String id, String auditCat, String auditResult, String auditRemark, OptVo optVo) {
        SAuditRecord sAuditRecord = new SAuditRecord();
        sAuditRecord.setBussId(id);
        sAuditRecord.setBussType("company");
        sAuditRecord.setAuditCat(auditCat);
        sAuditRecord.setId(IdUtil.simpleUUID());
        sAuditRecord.setBussId(id);
        sAuditRecord.setAuditResult(auditResult);
        sAuditRecord.setAuditRemark(auditRemark);
        sAuditRecord.setAuditId(optVo.getUserId());
        sAuditRecord.setAuditName(optVo.getUserName());
        sAuditRecord.setAuditDate(new Date());
        sAuditRecord.setDeleted("n");
        sAuditRecord.setCreatedId(optVo.getUserId());
        sAuditRecord.setCreatedDate(new Date());
        sAuditRecord.setUpdateId(optVo.getUserId());
        sAuditRecord.setUpdateDate(new Date());
        return sAuditRecord;
    }

    /**
     * 供应商信息撤回
     *
     * @param id
     */
    public void withdrawCompany(String id) {
        SCompanyInfo sCompanyInfo = sCompanyInfoMapper.selectByPrimaryKey(id);
        if (sCompanyInfo == null) {
            throw new BizException("该供应商不存在，请核实供应商id");
        }
        String state = sCompanyInfo.getState();
        // 修改为所有状态均可撤销
        if (!ComStateEnum.WC.name().equals(state)) {
            sCompanyInfo.setState(ComStateEnum.WC.name());
            sCompanyInfoMapper.updateByPrimaryKeySelective(sCompanyInfo);
        } else {
            throw new BizException("供应商当前状态不允许撤回");
        }
    }

    /**
     * 供应商下拉列表查询
     *
     * @return id, name
     */
    public List<JSONObject> queryList(JSONObject obj) {
        return sCompanyMapper.selectCompanyList(obj);
    }

    /**
     * 供应商报表查询
     *
     * @param reportQueryReqPojo
     */
    public Page<ProjectReportPojo> queryCompanyReport(ReportQueryReqPojo reportQueryReqPojo) {
        ReportParamData paramData = reportQueryReqPojo.getParamData();
        PageHelper.startPage(reportQueryReqPojo.getPageNo(), reportQueryReqPojo.getPageSize());
        Page<ProjectReportPojo> sProjectInfoList = (Page<ProjectReportPojo>) sProjectMapper.selectProjectAndCompany(paramData);
//        int total = (int) page.getTotal();
//        ReportQueryRespPojo reportQueryRespPojo = new ReportQueryRespPojo();
        sProjectInfoList.forEach(this::fillAttr);
        sProjectInfoList.sort(Comparator.comparing(ProjectReportPojo::getCreatedDate).reversed().thenComparing(ProjectReportPojo::getId));
        return sProjectInfoList;
    }

    /**
     * 供应商报表导出
     *
     * @param paramData
     * @param response
     */
    public void exportCompanyReport(ReportParamData paramData, HttpServletResponse response) {
        List<ProjectReportPojo> sProjectInfoList = sProjectMapper.selectProjectAndCompany(paramData);
        sProjectInfoList.forEach(this::fillAttr);
        sProjectInfoList.sort(Comparator.comparing(ProjectReportPojo::getCreatedDate).reversed().thenComparing(ProjectReportPojo::getId));
        for (int i = 0; i < sProjectInfoList.size(); i++) {
            sProjectInfoList.get(i).setSortNum(i + 1);
        }
        // 开始将数据转换成Excel数据
        try {
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("供应商报表" + DateUtil.today(), "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            EasyExcel.write(response.getOutputStream(), ProjectReportPojo.class).inMemory(Boolean.TRUE).sheet("供应商列表").doWrite(sProjectInfoList);
        } catch (IOException e) {
            logger.error("errorMessage:", e);
        }
    }

    private void fillAttr(ProjectReportPojo e) {
        String id = e.getId();
        CompanyInfoPojo companyInfoPojo = queryCompanyDetail(e.getCompanyId());
        BeanUtil.copyProperties(companyInfoPojo, e);
        List<Contract> contractList = companyInfoPojo.getContracts();
        if (CollUtil.isNotEmpty(contractList)) {
            e.setContactNames(contractList.stream().map(Contract::getContactName).collect(Collectors.joining(",")));
            e.setContactPhones(contractList.stream().map(Contract::getContactPhone).collect(Collectors.joining(",")));
            e.setContactEmails(contractList.stream().map(Contract::getContactEmail).collect(Collectors.joining(",")));
            e.setContactPositions(contractList.stream().map(Contract::getContactPosition).collect(Collectors.joining(",")));
        }
        e.setSupplierScopeCatName(commonBizService.transCatWithList(companyInfoPojo.getSupplierScope()));
//            if (StrUtil.isNotEmpty(companyInfoPojo.getPermitStartDate()) && StrUtil.isNotEmpty(companyInfoPojo.getPermitEndDate())) {
//                e.setPermitStartEndDate(companyInfoPojo.getPermitStartDate().substring(0, 10) + "至" + companyInfoPojo.getPermitEndDate().substring(0, 10));
//            }
        if (StrUtil.isNotEmpty(companyInfoPojo.getLicenseStartDate()) && StrUtil.isNotEmpty(companyInfoPojo.getLicenseEndDate())) {
            e.setLicenseStartEndDate(companyInfoPojo.getLicenseStartDate().substring(0, 10) + "至" + companyInfoPojo.getLicenseEndDate().substring(0, 10));
        }
        e.setId(id);
        e.setJoinInFlagName("Y".equals(e.getJoinInFlag())? "是" : "否");
        SEvaluateRecord sEvaluateRecord = new SEvaluateRecord();
        sEvaluateRecord.setDeleted("n");
        sEvaluateRecord.setCompanyId(e.getCompanyId());
        sEvaluateRecord.setProjectId(e.getId());
        List<SEvaluateRecord> sEvaluateRecordList = sEvaluateRecordMapper.select(sEvaluateRecord);
        if (CollUtil.isNotEmpty(sEvaluateRecordList)) {
            List<SEvaluateRecord> pfmEvaluate = sEvaluateRecordList.stream().filter(evaluateRecord -> AppraiseEnum.agree.name().equals(evaluateRecord.getEvaCatCode())).collect(Collectors.toList());
            e.setPfmEvaluateScore(pfmEvaluate.stream().mapToInt(record -> {
                try {
                    return Integer.parseInt(record.getScore());
                } catch (NumberFormatException ex) {
                    return 0;
                }
            }).sum());
            List<SEvaluateRecord> prcEvaluate = sEvaluateRecordList.stream().filter(evaluateRecord -> AppraiseEnum.buy.name().equals(evaluateRecord.getEvaCatCode())).collect(Collectors.toList());
            e.setPrcEvaluateScore(prcEvaluate.stream().mapToInt(record ->{
                try {
                    return  Integer.parseInt(record.getScore());
                } catch (NumberFormatException ex) {
                    return 0;
                }
            }).sum());
        }
    }

    public static String bizType = "company";

    /**
     * 法务是否审核过
     * @param bizId
     * @return
     */
    public boolean hasAuditPass(String bizId) {
        Example exp = new Example(SAuditRecord.class);
        exp.createCriteria().andEqualTo("bussId", bizId).andEqualTo("bussType", bizType).andEqualTo("auditCat", "legal2")
                .andEqualTo("auditResult", "Y");
        int i = sAuditRecordMapper.selectCountByExample(exp);
        return i>0;
    }
    private SAuditRecord addAuditRecord(OptVo optVo, String bizId, String fileType, String auditRes, String remark) {
        SAuditRecord record = new SAuditRecord();
        record.setId(IdUtil.simpleUUID());
        record.setBussId(bizId);
        record.setBussType(bizType);
        record.setAuditCat(fileType);
        record.setAuditId(optVo.getUserId());
        record.setAuditName(optVo.getUserName());
        record.setAuditDate(DateUtil.date());
        record.setDeleted("n");
        record.setCreatedId(optVo.getUserId());
        record.setCreatedDate(DateUtil.date());
        record.setUpdateDate(DateUtil.date());
        record.setAuditRemark(remark);
        record.setAuditResult(auditRes);
        sAuditRecordMapper.insert(record);
        return record;
    }

    public ModQueryVo modHisList(String id) {
        SCompanyInfo sCompanyInfo = sCompanyInfoMapper.selectByPrimaryKey(id);
        if (sCompanyInfo == null) {
            throw new BizException("该供应商不存在，请核实供应商id");
        }
        List<ModQueryVo.ModItem> items = new ArrayList<>();
        ModQueryVo queryVo = new ModQueryVo();
        queryVo.setName(sCompanyInfo.getName());
        queryVo.setSocialCreditCode(sCompanyInfo.getSocialCreditCode());
        queryVo.setLegalPerson(sCompanyInfo.getLegalPerson());
        queryVo.setItems(items);

        Example exp = new Example(SCompanyInfoModifying.class);
        exp.createCriteria().andEqualTo("bussId", id);
        exp.orderBy("createdDate").desc();
        List<SCompanyInfoModifying> sCompanyInfoModifyings = sCompanyInfoModifyingMapper.selectByExample(exp);
        if (CollUtil.isNotEmpty(sCompanyInfoModifyings)) {
            for (SCompanyInfoModifying sCompanyInfoModifying : sCompanyInfoModifyings) {
                ModQueryVo.ModItem item = new ModQueryVo.ModItem();
                item.setCategory("mod");
                item.setCreatedDate(DateUtil.formatDateTime(sCompanyInfoModifying.getCreatedDate()));
                item.setBussId(sCompanyInfoModifying.getBussId());
                item.setId(sCompanyInfoModifying.getId());
                items.add(item);
            }
        }
        return queryVo;
    }

    public CompanyInfoPojo modHisDetail(String id) {
        return commonBizService.queryHisDetail(id);
    }

    public String valiPhone(ValiComInfoPojo comInfoPojo) {
        Example exp = new Example(SCompanyInfo.class);
        exp.createCriteria().andEqualTo("name", comInfoPojo.getName());
        int i = sCompanyInfoMapper.selectCountByExample(exp);
        if (i == 0) {
            throw new BizException("该公司尚未注册过，无法登录，请联系我司管理员进行注册");
        }
        List<JSONObject> jsonObjects = sCompanyMapper.queryByNameAndPhone(comInfoPojo);
        if (CollUtil.isEmpty(jsonObjects)) {
            throw new BizException("请使用正确的联系人手机号登录");
        }
        if (jsonObjects.size()>1) {
            throw new BizException("联系人信息重复，暂无法登录");
        }
        String companyId = jsonObjects.get(0).getString("companyId");
        if (StrUtil.isEmpty(companyId)) {
            throw new BizException("该公司尚未注册过，无法登录，请联系我司管理员进行注册");
        }
        return companyId;
    }

    @Transactional
    public void markSubmit(CompanyMarkReq markReq, OptVo optVo) {
        // 查询供应商是否存在
        SCompanyInfo sCompanyInfoDb = sCompanyInfoMapper.selectByPrimaryKey(markReq.getCompanyId());
        if (sCompanyInfoDb == null) {
            throw new BizException("该供应商不存在，请核实供应商id");
        }
        String markStatus = markReq.getMarkStatus();
        // 校验延长停用时间止期是否大于上一个审批通过的止期
//        if (MarkStateEnum.blackadd.name().equals(markStatus) || MarkStateEnum.stopadd.name().equals(markStatus)) {
//            Date beforeStopDate = sCompanyMapper.selectBeforeStopDate(sCompanyInfoDb.getMarkId());
//            logger.info("beforeStopDate==>{}", beforeStopDate);
//        }
        // 插入标记记录表
        SCompanyMark companyInfoMark = new SCompanyMark();
        BeanUtils.copyProperties(markReq, companyInfoMark);
        companyInfoMark.setId(IdUtil.simpleUUID());
        companyInfoMark.setCreatedId(optVo.getUserId());
        companyInfoMark.setCreatedName(optVo.getUserName());
        companyInfoMark.setCreatedDate(DateUtil.date());
        companyInfoMark.setMarkAuditStatus("n");
        companyInfoMark.setDeleted("n");
        sCompanyMarkMapper.insert(companyInfoMark);
        // 更新主表标记关联id
        SCompanyInfo sCompanyInfo = new SCompanyInfo();
        sCompanyInfo.setId(markReq.getCompanyId());
        sCompanyInfo.setMarkId(companyInfoMark.getId());
        sCompanyMapper.updateCompanyMarkInfo(sCompanyInfo);
        // 更新修改表标记关联id
        // 更新修改表标记
        sCompanyMapper.updateCompanyModifyMarkInfo(markReq.getCompanyId());
        if (!CollUtil.isEmpty(markReq.getMarkFiles())) {
            // 插入关联文件表
            List<SCompanyFile> sCompanyFileList = new ArrayList<>();
            markReq.getMarkFiles().forEach(file -> {
                SCompanyFile sCompanyFile = addFile(sCompanyInfo, FileTypeEnum.MAPJF.name(), file.getFilePath());
                sCompanyFile.setBizId(companyInfoMark.getId());
                sCompanyFile.setBizType("mark");
                sCompanyFileList.add(sCompanyFile);
            });
            sCompanyFileMapper.insertList(sCompanyFileList);
        }
    }

    public List<CompanyMarkHisListResp> markHisList(JSONObject jsonObject) {
        String companyId = jsonObject.getString("companyId");
        int pageSize = jsonObject.getIntValue("pageSize");
        int pageNo = jsonObject.getIntValue("pageNo");
//        PageHelper.startPage(pageNo, pageSize);
        List<CompanyMarkHisListResp> companyMarkHisList = sCompanyMapper.selectMarkHisList(companyId);
        // 查询提交和审核附件
        companyMarkHisList.forEach(mark -> {
            mark.setApplyFiles(sCompanyMapper.selectMarkFile(FileTypeEnum.MAPJF.name(), mark.getMarkId()));
            mark.setAuditFiles(sCompanyMapper.selectMarkFile(FileTypeEnum.MAUJF.name(), mark.getMarkAuditId()));
        });
        return companyMarkHisList;
    }

    @Transactional
    public void markAuditSubmit(CompanyMarkAuditReq markAuditReq, OptVo optVo) {
        String companyId = markAuditReq.getCompanyId();
        String markId = markAuditReq.getMarkId();
        String auditResult = markAuditReq.getAuditResult();
        String auditRemark = markAuditReq.getAuditRemark();
        SCompanyMark companyMark = sCompanyMapper.selectMarkInfo(markId);
        if (companyMark == null) {
            throw new BizException("供应商标记申请记录不存在");
        }
        // 审核记录入库
        SAuditRecord sAuditRecord = getAuditRecord(companyId, "mark", auditResult, auditRemark, optVo);
        sAuditRecordMapper.insert(sAuditRecord);
        // 审核文件入库
        if (!CollUtil.isEmpty(markAuditReq.getMarkAuditFiles())) {
            // 插入关联文件表
            List<SCompanyFile> sCompanyFileList = new ArrayList<>();
            SCompanyInfo sCompanyInfo = new SCompanyInfo();
            sCompanyInfo.setId(markAuditReq.getCompanyId());
            markAuditReq.getMarkAuditFiles().forEach(file -> {
                SCompanyFile sCompanyFile = addFile(sCompanyInfo, FileTypeEnum.MAUJF.name(), file.getFilePath());
                sCompanyFile.setBizId(sAuditRecord.getId());
                sCompanyFile.setBizType("mark");
                sCompanyFileList.add(sCompanyFile);
            });
            sCompanyFileMapper.insertList(sCompanyFileList);
        }
        // 更新标记表信息
        companyMark.setMarkAuditId(sAuditRecord.getId());
        companyMark.setMarkAuditStatus("y");
        companyMark.setUpdateId(optVo.getUserId());
        companyMark.setUpdateDate(DateUtil.date());
        sCompanyMarkMapper.updateByPrimaryKey(companyMark);
        // 审批通过且延长停用时间不更新主表标记状态
        if ("y".equals(auditResult) && !MarkStateEnum.blackadd.name().equals(companyMark.getMarkStatus())
                && !MarkStateEnum.stopadd.name().equals(companyMark.getMarkStatus())) {
            // 更新主表标记
            SCompanyInfo sCompanyInfo = new SCompanyInfo();
            sCompanyInfo.setId(companyId);
            sCompanyInfo.setMarkStatus(companyMark.getMarkStatus());
            sCompanyMapper.updateCompanyMarkInfo(sCompanyInfo);
            // 更新修改表标记
            sCompanyMapper.updateCompanyModifyMarkInfo(companyId);
        }
    }



    public List<CompanyMarkQueryResp> markQuery(CompanyQueryReqPojo companyQueryReqPojo, OptVo optVo) {
        CompanyQueryReqPojo.ParamData paramData = companyQueryReqPojo.getParamData();
        //        PageHelper.startPage(companyQueryReqPojo.getPageNo(), companyQueryReqPojo.getPageSize());

//        Page<CompanyMarkQueryResp> companyMarkList = (Page<CompanyMarkQueryResp>) sCompanyMapper.selectCompanyMark(paramData);
        List<CompanyMarkQueryResp> companyMarkList = sCompanyMapper.selectCompanyMark(paramData);
        return companyMarkList;
    }

    public void noticeSendEmail(JSONObject jsonObject) {
        String id = jsonObject.getString("id");
        SCompanyInfo companyInfo = sCompanyInfoMapper.selectByPrimaryKey(id);
        if (companyInfo == null) {
            throw new BizException("供应商不存在");
        }
        supSendService.notifyContractModify(companyInfo);
    }



}
